<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第18篇：包和依赖管理, 张亚飞,飞凡空间,国学,Python,Go">
    <meta name="description" content="一、包（package）一般来说，一个文件夹可以作为 package，同一个 package 内部变量、类型、方法等定义可以相互看到。Go语言的包具有以下特点：

package是Go语言的基本复用模块单元。
注：以首字母大小写来区分是否可">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-w2ezfaoXE0" />
    <title>第18篇：包和依赖管理 | 飞凡空间</title>
    <link rel="icon" type="image/png" href="/medias/my-logo.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    
    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="飞凡空间" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/my-logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">飞凡空间</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/my-logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">飞凡空间</div>
        <div class="logo-desc">
            
            诚者，天之道也；诚之者，人之道也。诚者，不勉而中，不思而得。从容中道，圣人也；诚之者，择善而固执者也。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/18.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第18篇：包和依赖管理
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                                <span class="chip bg-color">Go之路</span>
                            </a>
                        
                            <a href="/tags/%E5%8C%85/">
                                <span class="chip bg-color">包</span>
                            </a>
                        
                            <a href="/tags/%E4%BE%9D%E8%B5%96%E7%AE%A1%E7%90%86/">
                                <span class="chip bg-color">依赖管理</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Go/" class="post-category">
                                Go
                            </a>
                        
                            <a href="/categories/Go/base/" class="post-category">
                                base
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-01-01
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2.4k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    10 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、包（package）"><a href="#一、包（package）" class="headerlink" title="一、包（package）"></a>一、包（package）</h2><p>一般来说，一个文件夹可以作为 package，同一个 package 内部变量、类型、方法等定义可以相互看到。Go语言的包具有以下特点：</p>
<ol>
<li><p>package是Go语言的基本复用模块单元。</p>
<p><strong>注：以首字母大小写来区分是否可被包外代码访问。</strong></p>
</li>
</ol>
<blockquote>
<p>大写代表，可以被包外引入。<br>小写代表，不可被包外引入。</p>
</blockquote>
<ol start="2">
<li><p>package名可以与目录名不一致。（但建议一致）</p>
</li>
<li><p>同一目录下的Go文件，必须属于同一个package。</p>
</li>
</ol>
<h3 id="1-可见性"><a href="#1-可见性" class="headerlink" title="1. 可见性"></a>1. 可见性</h3><p><strong>包中的变量、函数和方法等以首字母大小写来区分是否可被包外代码访问。</strong></p>
<blockquote>
<p>大写代表，可以被包外引入。<br>小写代表，不可被包外引入。</p>
</blockquote>
<p>比如我们新建一个文件 <code>calc.go</code>， <code>main.go</code> 平级，分别定义 add 和 main 方法。</p>
<ul>
<li><p>calc.go</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">func</span> <span class="token function">add</span><span class="token punctuation">(</span>num1 <span class="token builtin">int</span><span class="token punctuation">,</span> num2 <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> num1 <span class="token operator">+</span> num2
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>main.go</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 8</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>运行 <code>go run main.go</code>，会报错，add 未定义：</p>
<pre class="line-numbers language-shell"><code class="language-shell">./main.go:6:14: undefined: add<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>因为 <code>go run main.go</code> 仅编译 main.go 一个文件，所以命令需要换成</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go run main.go calc.go
8<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>或</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go run .
8<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>Go 语言也有 Public 和 Private 的概念，粒度是包。如果类型/接口/方法/函数/字段的首字母大写，则是 Public 的，对其他 package 可见，如果首字母小写，则是 Private 的，对其他 package 不可见。</p>
</li>
</ul>
<h3 id="2-init和main函数"><a href="#2-init和main函数" class="headerlink" title="2.  init和main函数"></a>2.  init和main函数</h3><h4 id="2-1-init函数"><a href="#2-1-init函数" class="headerlink" title="2.1 init函数"></a>2.1 init函数</h4><p>go语言中<code>init</code>函数用于包<code>(package)</code>的初始化，该函数是go语言的一个重要特性。</p>
<p>有下面的特征：</p>
<ul>
<li>init函数是用于程序执行前做包的初始化的函数，比如初始化包里的变量等</li>
<li>每个包可以拥有多个init函数</li>
<li>包的每个源文件也可以拥有多个init函数</li>
<li>同一个包中多个init函数的执行顺序go语言没有明确的定义(说明)</li>
<li>不同包的init函数按照包导入的依赖关系决定该初始化函数的执行顺序</li>
<li>init函数不能被其他函数调用，而是在main函数执行之前，自动被调用</li>
</ul>
<h4 id="2-2-main函数"><a href="#2-2-main函数" class="headerlink" title="2.2 main函数"></a>2.2 main函数</h4><pre class="line-numbers language-go"><code class="language-go">Go语言程序的默认入口函数<span class="token punctuation">(</span>主函数<span class="token punctuation">)</span>：<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
函数体用｛｝一对括号包裹。

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
<span class="token comment" spellcheck="true">//函数体</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-3-init函数和main函数的异同"><a href="#2-3-init函数和main函数的异同" class="headerlink" title="2.3 init函数和main函数的异同"></a>2.3 init函数和main函数的异同</h4><pre><code>相同点：
两个函数在定义时不能有任何的参数和返回值，且Go程序自动调用。
不同点：
init可以应用于任意包中，且可以重复定义多个。
main函数只能用于main包中，且只能定义一个。</code></pre>
<p>两个函数的执行顺序：</p>
<ul>
<li>对同一个go文件的<code>init()</code>调用顺序是从上到下的。</li>
<li>对同一个package中不同文件是按文件名字符串比较“从小到大”顺序调用各文件中的<code>init()</code>函数。</li>
<li>对于不同的<code>package</code>，如果不相互依赖的话，按照main包中”先<code>import</code>的后调用”的顺序调用其包中的<code>init()</code>，如果<code>package</code>存在依赖，则先调用最早被依赖的<code>package</code>中的<code>init()</code>，最后调用<code>main</code>函数。</li>
<li>如果<code>init</code>函数中使用了<code>println()</code>或者<code>print()</code>你会发现在执行过程中这两个不会按照你想象中的顺序执行。这两个函数官方只推荐在测试环境中使用，对于正式环境不要使用。</li>
</ul>
<h2 id="二、依赖管理"><a href="#二、依赖管理" class="headerlink" title="二、依赖管理"></a>二、依赖管理</h2><h3 id="1-为什么使用是依赖管理"><a href="#1-为什么使用是依赖管理" class="headerlink" title="1. 为什么使用是依赖管理"></a>1. 为什么使用是依赖管理</h3><p>最早的时候，Go所依赖的所有的第三方库都放在GOPATH这个目录下面。这就导致了同一个库只能保存一个版本的代码。如果不同的项目依赖同一个第三方的库的不同版本，应该怎么解决？</p>
<h3 id="2-go-module"><a href="#2-go-module" class="headerlink" title="2. go module"></a>2. go module</h3><p><code>go module</code>是Go1.11版本之后官方推出的版本管理工具，并且从Go1.13版本开始，<code>go module</code>将是Go语言默认的依赖管理工具。</p>
<h4 id="2-1-GO111MODULE"><a href="#2-1-GO111MODULE" class="headerlink" title="2.1 GO111MODULE"></a>2.1 GO111MODULE</h4><p>要启用<code>go module</code>支持首先要设置环境变量<code>GO111MODULE</code>，通过它可以开启或关闭模块支持，它有三个可选值：<code>off</code>、<code>on</code>、<code>auto</code>，默认值是<code>auto</code>。</p>
<ol>
<li><code>GO111MODULE=off</code>禁用模块支持，编译时会从<code>GOPATH</code>和<code>vendor</code>文件夹中查找包。</li>
<li><code>GO111MODULE=on</code>启用模块支持，编译时会忽略<code>GOPATH</code>和<code>vendor</code>文件夹，只根据 <code>go.mod</code>下载依赖。</li>
<li><code>GO111MODULE=auto</code>，当项目在<code>$GOPATH/src</code>外且项目根目录有<code>go.mod</code>文件时，开启模块支持。</li>
</ol>
<p>简单来说，设置<code>GO111MODULE=on</code>之后就可以使用<code>go module</code>了，以后就没有必要在GOPATH中创建项目了，并且还能够很好的管理项目依赖的第三方包信息。</p>
<p>使用 go module 管理依赖后会在项目根目录下生成两个文件<code>go.mod</code>和<code>go.sum</code>。</p>
<h4 id="2-2-go-mod命令"><a href="#2-2-go-mod命令" class="headerlink" title="2.2 go mod命令"></a>2.2 go mod命令</h4><p>常用的<code>go mod</code>命令如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">go</span> mod init        初始化当前文件夹<span class="token punctuation">,</span> 创建<span class="token keyword">go</span><span class="token punctuation">.</span>mod文件
<span class="token keyword">go</span> mod tidy        增加缺少的module，删除无用的module
<span class="token keyword">go</span> mod download    下载依赖的module到本地cache（默认为$GOPATH<span class="token operator">/</span>pkg<span class="token operator">/</span>mod目录）
<span class="token keyword">go</span> mod edit        编辑<span class="token keyword">go</span><span class="token punctuation">.</span>mod文件
<span class="token keyword">go</span> mod graph       打印模块依赖图
<span class="token keyword">go</span> mod vendor      将依赖复制到vendor下
<span class="token keyword">go</span> mod verify      校验依赖
<span class="token keyword">go</span> mod why         解释为什么需要依赖<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="go-init"><a href="#go-init" class="headerlink" title="go init"></a>go init</h5><pre class="line-numbers language-shell"><code class="language-shell">go mod init example<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>完成上述操作之后，就会在当前目录下生成一个go.mod文件，这个文件中的结构如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">//module 后面是当前项目的模块名称，一般与项目名称相同，但也可以不同</span>
module example

<span class="token comment" spellcheck="true">//预设的go版本</span>
<span class="token keyword">go</span> <span class="token number">1.13</span>

<span class="token comment" spellcheck="true">//用于将一个模块版本替换成另一个模块版本，前提是当前模块为主模块时,例如：</span>
replace k8s<span class="token punctuation">.</span>io<span class="token operator">/</span>api <span class="token operator">=</span><span class="token operator">></span> k8s<span class="token punctuation">.</span>io<span class="token operator">/</span>api v0<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20190918155943</span><span class="token operator">-</span>95b840bb6a1f

<span class="token comment" spellcheck="true">//也可以用于引入本地的其他模块到当前这个模块中，例如：</span>
replace ecm<span class="token operator">-</span>sdk<span class="token operator">-</span><span class="token keyword">go</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">.</span><span class="token operator">/</span>vendor<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>util

<span class="token comment" spellcheck="true">//当前项目中的依赖列表</span>
<span class="token function">require</span> <span class="token punctuation">(</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>git<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>git<span class="token operator">/</span>v5 v5<span class="token number">.1</span><span class="token punctuation">.</span><span class="token number">0</span>
<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">//当前项目中禁止依赖包列表</span>
<span class="token function">exclude</span> <span class="token punctuation">(</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>git<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>git<span class="token operator">/</span>v5 v5<span class="token number">.1</span><span class="token punctuation">.</span><span class="token number">0</span>
<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="go-get"><a href="#go-get" class="headerlink" title="go get"></a>go get</h5><ul>
<li><code>go get packageName</code>：安装依赖</li>
<li><code>go get -u</code> packageName：将依赖升级到最新的次要版本或修订版本</li>
<li><code>go get -u=patch packageName</code>：将依赖升级到最新的修订版本</li>
<li><code>go get package@version</code>：升级到指定的版本</li>
</ul>
<pre class="line-numbers language-shell"><code class="language-shell">go get github.com/kataras/iris@master<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>如果下载所有依赖可以使用<code>go mod download</code>命令。</p>
<p>go.mod文件记录了项目所有的依赖信息，其结构大致如下：</p>
<pre class="line-numbers language-go"><code class="language-go">module example

<span class="token keyword">go</span> <span class="token number">1.12</span>

<span class="token function">require</span> <span class="token punctuation">(</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>sql<span class="token operator">-</span>driver<span class="token operator">/</span>mysql v1<span class="token number">.4</span><span class="token punctuation">.</span><span class="token number">1</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span>golang<span class="token operator">/</span>protobuf v1<span class="token number">.3</span><span class="token punctuation">.</span><span class="token number">2</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span>grpc<span class="token operator">-</span>ecosystem<span class="token operator">/</span>grpc<span class="token operator">-</span>gateway v1<span class="token number">.11</span><span class="token punctuation">.</span><span class="token number">3</span> <span class="token comment" spellcheck="true">// indirect</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span>jmoiron<span class="token operator">/</span>sqlx v1<span class="token number">.2</span><span class="token punctuation">.</span><span class="token number">0</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span>micro<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>micro v1<span class="token number">.12</span><span class="token punctuation">.</span><span class="token number">0</span>
    github<span class="token punctuation">.</span>com<span class="token operator">/</span>prometheus<span class="token operator">/</span>client_model v0<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20190812154241</span><span class="token operator">-</span>14fe0d1b01d4 <span class="token comment" spellcheck="true">// indirect</span>
    <span class="token keyword">go</span><span class="token punctuation">.</span>uber<span class="token punctuation">.</span>org<span class="token operator">/</span>zap v1<span class="token number">.10</span><span class="token punctuation">.</span><span class="token number">0</span>
    google<span class="token punctuation">.</span>golang<span class="token punctuation">.</span>org<span class="token operator">/</span>grpc v1<span class="token number">.24</span><span class="token punctuation">.</span><span class="token number">0</span>
    gopkg<span class="token punctuation">.</span>in<span class="token operator">/</span>natefinch<span class="token operator">/</span>lumberjack<span class="token punctuation">.</span>v2 v2<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span>
<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其中，</p>
<ul>
<li><code>module</code>用来定义包名</li>
<li><code>require</code>用来定义依赖包及版本</li>
<li><code>indirect</code>表示间接引用</li>
</ul>
<h5 id="依赖的版本"><a href="#依赖的版本" class="headerlink" title="依赖的版本"></a>依赖的版本</h5><p>go mod支持语义化版本号，比如<code>go get foo@v1.2.3</code>，也可以跟git的分支或tag，比如<code>go get foo@master</code>，当然也可以跟git提交哈希，比如<code>go get foo@e3702bed2</code>。关于依赖的版本支持以下几种格式：</p>
<pre class="line-numbers language-go"><code class="language-go">gopkg<span class="token punctuation">.</span>in<span class="token operator">/</span>tomb<span class="token punctuation">.</span>v1 v1<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20141024135613</span><span class="token operator">-</span>dd632973f1e7
gopkg<span class="token punctuation">.</span>in<span class="token operator">/</span>vmihailenco<span class="token operator">/</span>msgpack<span class="token punctuation">.</span>v2 v2<span class="token number">.9</span><span class="token punctuation">.</span><span class="token number">1</span>
gopkg<span class="token punctuation">.</span>in<span class="token operator">/</span>yaml<span class="token punctuation">.</span>v2 <span class="token operator">&lt;=</span>v2<span class="token number">.2</span><span class="token punctuation">.</span><span class="token number">1</span>
github<span class="token punctuation">.</span>com<span class="token operator">/</span>tatsushid<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>fastping v0<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20160109021039</span><span class="token operator">-</span>d7bb493dee3e
latest<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="replace"><a href="#replace" class="headerlink" title="replace"></a>replace</h5><p>在国内访问golang.org/x的各个包都需要翻墙，你可以在go.mod中使用replace替换成github上对应的库。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token function">replace</span> <span class="token punctuation">(</span>
    golang<span class="token punctuation">.</span>org<span class="token operator">/</span>x<span class="token operator">/</span>crypto v0<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20180820150726</span><span class="token operator">-</span>614d502a4dac <span class="token operator">=</span><span class="token operator">></span> github<span class="token punctuation">.</span>com<span class="token operator">/</span>golang<span class="token operator">/</span>crypto v0<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20180820150726</span><span class="token operator">-</span>614d502a4dac
    golang<span class="token punctuation">.</span>org<span class="token operator">/</span>x<span class="token operator">/</span>net v0<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20180821023952</span><span class="token operator">-</span>922f4815f713 <span class="token operator">=</span><span class="token operator">></span> github<span class="token punctuation">.</span>com<span class="token operator">/</span>golang<span class="token operator">/</span>net v0<span class="token number">.0</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">-</span><span class="token number">20180826012351</span><span class="token operator">-</span>8a410e7b638d
    golang<span class="token punctuation">.</span>org<span class="token operator">/</span>x<span class="token operator">/</span>text v0<span class="token number">.3</span><span class="token punctuation">.</span><span class="token number">0</span> <span class="token operator">=</span><span class="token operator">></span> github<span class="token punctuation">.</span>com<span class="token operator">/</span>golang<span class="token operator">/</span>text v0<span class="token number">.3</span><span class="token punctuation">.</span><span class="token number">0</span>
<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="整理依赖"><a href="#整理依赖" class="headerlink" title="整理依赖"></a>整理依赖</h5><p>我们在代码中删除依赖代码后，相关的依赖库并不会在<code>go.mod</code>文件中自动移除。这种情况下我们可以使用<code>go mod tidy</code>命令更新<code>go.mod</code>中的依赖关系。</p>
<h5 id="go-mod-edit"><a href="#go-mod-edit" class="headerlink" title="go mod edit"></a>go mod edit</h5><p><strong>格式化</strong></p>
<p>因为我们可以手动修改go.mod文件，所以有些时候需要格式化该文件。Go提供了一下命令：</p>
<pre class="line-numbers language-shell"><code class="language-shell">go mod edit -fmt<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><strong>添加依赖项</strong></p>
<pre class="line-numbers language-shell"><code class="language-shell">go mod edit -require=golang.org/x/text<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><strong>移除依赖项</strong></p>
<p>如果只是想修改<code>go.mod</code>文件中的内容，那么可以运行<code>go mod edit -droprequire=package path</code>，比如要在<code>go.mod</code>中移除<code>golang.org/x/text</code>包，可以使用如下命令：</p>
<pre class="line-numbers language-shell"><code class="language-shell">go mod edit -droprequire=golang.org/x/text<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>关于<code>go mod edit</code>的更多用法可以通过<code>go help mod edit</code>查看。</p>
<h4 id="2-3-在项目中使用-go-module"><a href="#2-3-在项目中使用-go-module" class="headerlink" title="2.3  在项目中使用 go module"></a>2.3  在项目中使用 go module</h4><p>在一个空文件夹下，初始化一个 Module</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go mod init example
go: creating new go.mod: module example<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>此时，在当前文件夹下生成了<code>go.mod</code>，这个文件记录当前模块的模块名以及所有依赖包的版本。</p>
<p>接着，我们在当前目录下新建文件 <code>main.go</code>，添加如下代码：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>

    <span class="token string">"rsc.io/quote"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>quote<span class="token punctuation">.</span><span class="token function">Hello</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true">// Ahoy, world!</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>运行 <code>go run .</code>，将会自动触发第三方包 <code>rsc.io/quote</code>的下载，具体的版本信息也记录在了<code>go.mod</code>中：</p>
<pre class="line-numbers language-go"><code class="language-go">module example

<span class="token keyword">go</span> <span class="token number">1.13</span>

require rsc<span class="token punctuation">.</span>io<span class="token operator">/</span>quote v3<span class="token number">.1</span><span class="token punctuation">.</span><span class="token number">0</span><span class="token operator">+</span>incompatible<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>go run</code>命令会直接下载依赖并且运行项目文件，如果我们只想下载依赖可以使用<code>go mod tidy</code>命令。</p>
<pre class="line-numbers language-shell"><code class="language-shell">go mod tidy<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>这时go编译器会去查找<code>go mod</code>和项目文件，增加缺少的module，删除无用的module。</p>
<p>我们在当前目录，添加一个子 package calc，代码目录如下：</p>
<pre><code>demo/
   |--calc/
      |--calc.go
   |--main.go</code></pre>
<p>在 <code>calc.go</code> 中写入</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> calc

<span class="token keyword">func</span> <span class="token function">Add</span><span class="token punctuation">(</span>num1 <span class="token builtin">int</span><span class="token punctuation">,</span> num2 <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> num1 <span class="token operator">+</span> num2
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在 package main 中如何使用 package cal 中的 Add 函数呢？<code>import 模块名/子目录名</code> 即可，修改后的 main 函数如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>
    <span class="token string">"example/calc"</span>

    <span class="token string">"rsc.io/quote"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>quote<span class="token punctuation">.</span><span class="token function">Hello</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>calc<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
$ <span class="token keyword">go</span> run <span class="token punctuation">.</span>
Ahoy<span class="token punctuation">,</span> world<span class="token operator">!</span>
<span class="token number">13</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io" rel="external nofollow noreferrer">张亚飞</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io/go/base/di-18-pian-bao-he-yi-lai/">https://zhangyafeii.gitee.io/go/base/di-18-pian-bao-he-yi-lai/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                                    <span class="chip bg-color">Go之路</span>
                                </a>
                            
                                <a href="/tags/%E5%8C%85/">
                                    <span class="chip bg-color">包</span>
                                </a>
                            
                                <a href="/tags/%E4%BE%9D%E8%B5%96%E7%AE%A1%E7%90%86/">
                                    <span class="chip bg-color">依赖管理</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b9bf0e29501275f4f23c',
        clientSecret: '1c56bc88fdb7b23ee3712916a38e5e8d1311823a',
        repo: 'github.io',
        owner: 'zhangyafeii',
        admin: "zhangyafeii",
        id: '2021-01-01T20-00-00',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/go/base/di-19-pian-bing-fa-bian-cheng-1/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/19.jpg" class="responsive-img" alt="第19篇：并发编程1">
                        
                        <span class="card-title">第19篇：并发编程1</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            一、并发介绍1. 进程、线程和协程
进程是程序在操作系统中的一次执行过程，系统进行资源分配和调度的一个独立单位。
线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。
一个程序至少有一个进程，一个进
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-01-02
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Go/" class="post-category">
                                    Go
                                </a>
                            
                            <a href="/categories/Go/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Go之路</span>
                    </a>
                    
                    <a href="/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">
                        <span class="chip bg-color">并发编程</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/go/practice/shi-zhan-pian-1-pa-chong-xiao-an-li/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/spider-1.jpg" class="responsive-img" alt="实战篇1：爬虫小案例">
                        
                        <span class="card-title">实战篇1：爬虫小案例</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            一、爬虫步骤
明确目标（确定在哪个网站搜索）
爬（爬下内容）
取（筛选想要的）
处理数据（按照你的想法去处理）

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-01-01
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Go/" class="post-category">
                                    Go
                                </a>
                            
                            <a href="/categories/Go/practice/" class="post-category">
                                    practice
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Go之路</span>
                    </a>
                    
                    <a href="/tags/%E5%AE%9E%E6%88%98%E7%AF%87/">
                        <span class="chip bg-color">实战篇</span>
                    </a>
                    
                    <a href="/tags/%E7%88%AC%E8%99%AB/">
                        <span class="chip bg-color">爬虫</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 飞凡空间<br />'
            + '文章作者: 张亚飞<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">344.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "12";
                    var startDate = "18";
                    var startHour = "12";
                    var startMinute = "12";
                    var startSecond = "12";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的Gitee" data-position="top" data-delay="50">
        <i class="fab fa-google-plus"></i>
    </a>



    <a href="mailto:zhangyafeii@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1271570224" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1271570224" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/js/cursor.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
